<template>
	<div class="manager-container">
		<!-- 搜索条件开始-->
		<!-- <div class="search"> -->
		<el-row :gutter="20">
			<!-- 搜索条件开始 -->
			<el-col :span="16">
				<el-form :model="queryParams" ref="queryForm" :inline="true" class="manager-search">
					<!-- 替换内容块开始 -->
					<el-col :span="8">
						<el-form-item label="表名" prop="tableName">
							<el-input v-model="queryParams.tableName" placeholder="请输入表名" clearable style="width: 200px"
								@keyup.enter="handleQuery" />
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="表注释" prop="tableTxt">
							<el-input v-model="queryParams.tableTxt" placeholder="请输入表注释" clearable style="width: 200px"
								@keyup.enter="handleQuery" />
						</el-form-item>
					</el-col>
					<!-- 替换内容块结束 -->
					<el-col :span="1.5">
						<el-button type="primary" @click="handleQuery" size="default">
							<i class="iconfont icon-chaxun btn-icon">查询</i>
						</el-button>
					</el-col>
					<el-col :span="1.5">
						<el-button @click="resetQuery" size="default">
							<i class="iconfont icon-chongzhi btn-icon">重置</i>
						</el-button>
					</el-col>
				</el-form>
			</el-col>
			<!-- 搜索条件结束 -->
			<!-- 工具条开始 -->
			<el-col :span="8">
				<el-row :gutter="20" style="float:right">
					<el-col :span="1.5">
						<!-- 替换内容块开始 -->
						<el-button type="primary" @click="handleAdd" size="default">
							<i class="iconfont icon-tianjia btn-icon">添加</i>
						</el-button>
					</el-col>
					<el-col :span="1.5">
						<el-button :disabled="multiple" @click="handleDelete" size="default" plain>
							<i class="iconfont icon-shanchu btn-icon">批量删除</i>
						</el-button>
					</el-col>
					<el-col :span="1.5">
						<el-button type="primary" size="default" @click="openImportTable">
							<i class="iconfont icon-daoru btn-icon">导入</i>
						</el-button>
					</el-col>
					<el-col :span="1.5">
						<el-button type="primary" @click="handleExport" size="default">
							<i class="iconfont icon-daochu btn-icon">导出</i>
						</el-button>
					</el-col>
					<!-- 替换内容块结束 -->
				</el-row>
			</el-col>
			<!-- 工具条结束 -->
		</el-row>
		<!-- </div> -->
		<!-- 搜索条件结束-->
		<!-- 主页面开始 -->
		<div class="table-list">
			<el-row :gutter="20" class="main-row">
				<!-- 表格开始 -->
				<el-col :span="24">
					<el-table :header-cell-style="{background:'#fafafa'}" :border="true" :data="tableList"
						@selection-change="handleSelectionChange" v-loading="loading" class="menu-table" height="550">
						<el-table-column type="selection" align="center" />
						<el-table-column label="表名" :show-overflow-tooltip="true" prop="tableName" />
						<el-table-column label="驼峰表名" :show-overflow-tooltip="true" prop="camelTableName">
							<template #default="scope">
								<div>
									{{scope.row.camelTableName || '-'}}
								</div>
							</template>
						</el-table-column>
						<el-table-column label="表注释" :show-overflow-tooltip="true" prop="tableTxt" />
						<el-table-column label="表单地址" :show-overflow-tooltip="true" prop="formId">
							<template #default="scope">
								<div>
									{{scope.row.formId || '-'}}
								</div>
							</template>
						</el-table-column>
						<el-table-column label="表单名称" :show-overflow-tooltip="true" prop="formName" />
						<el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="350">
							<template #default="scope">
								<el-button size="default" type="text" @click="handleUpdate(scope.row)">编辑</el-button>
								<el-divider direction="vertical"></el-divider>
								<el-button plain size="default" type="text" @click="handledetails(scope.row)">字段
								</el-button>
								<el-divider direction="vertical"></el-divider>
								<el-button plain size="default" type="text"
									@click="ChangetoggleModal('sh',true,scope.row.formId)">查看</el-button>
								<el-divider direction="vertical"></el-divider>
								<el-button plain size="default" type="text" @click="handleDelete(scope.row)">删除
								</el-button>
								<el-divider direction="vertical"></el-divider>
								<el-button plain size="default" type="text" @click="handleSjForm(scope.row)">设计
								</el-button>
								<el-divider direction="vertical"></el-divider>
								<el-button plain size="default" type="text" @click="generateCode(scope.row)">生成代码
								</el-button>
							</template>
						</el-table-column>
					</el-table>
					<Pagination :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
						@pagination="pagination" />
				</el-col>
				<!-- 表格结束 -->
			</el-row>
		</div>
		<!-- 主页面结束 -->
		<ModelS ref="shModal" :on-ok="handleIncreaseOk"></ModelS>
		<FormField ref="FormField" :formList="formList" v-if="FlagShow" @ok="handleQuery"></FormField>
		<import-table ref="import" @ok="handleQuery" />
		
		<el-dialog
		  title="请选择要生成的模块"
		  v-model="dialogVisible"
			width="45%"
			@close="cancleCreate"
		  custom-class="book-dialog">
		  <div>
				<el-form ref="createForm" :model="createParam" :rules="createRules" label-width="120px">
					<el-form-item label="包名" prop="packageName">
						<el-input v-model="createParam.packageName" placeholder="请输入包名" />
					</el-form-item>
					<el-form-item label="代码生成路径" prop="generatePath">
						<el-input v-model="createParam.generatePath" placeholder="请输入代码生成路径" />
					</el-form-item>
				</el-form>
				<div>
					<el-checkbox
						v-model="checkAll"
						:indeterminate="isIndeterminate"
						@change="handleCheckAllChange"
						>全选</el-checkbox
					>
				</div>
				<el-checkbox-group v-model="createParam.pages" @change="handleCheckedCitiesChange">
					<el-checkbox :label="item" v-for="(item, index) in optionsArr" :key="index" />
				</el-checkbox-group>
			</div>
		  <div slot="footer" class="dialog-footer" style="text-align: right;padding-top: 10px;">
		    <el-button @click="cancleCreate">取 消</el-button>
				<el-button type="primary" @click="submitCreate">确 定</el-button>
		  </div>
		</el-dialog>
		
	</div>
</template>

<script>
	//API接口
	import api from "@/api";
	//引入消息弹出框
	import {
		ElMessageBox,
		ElMessage
	} from "element-plus";
	//分页
	import ModelS from "./label.vue";
	import Pagination from "@/components/Pagination/index.vue";
	import FormField from "./sysFormField.vue";
	import importTable from "./importTable";
	import {
		getDicts
	} from "@/api/system/dict/data.js"
	import { getConfigKey } from "@/api/system/config";

	export default {
		components: {
			Pagination,
			ModelS,
			FormField,
			importTable
		},
		/**
		 * 定义变量
		 */
		data() {
			return {
				form: {}, //表单
				formList: {},
				isShow: true, //控制按钮状态
				FlagShow: false, //控制按钮状态
				value: "", //获取路由携带参数
				loading: false, //加载状态
				multiple: true, //控制头部删除按钮状态
				tableList: [], //表格列表
				total: 0, //总条目数
				isType: "add", //定义表单弹框的类型
				queryParams: {
					//查询参数
					pageNum: 1,
					pageSize: 10
				},
				// 生成代码
				dialogVisible: false,
				optionsArr: [],
				checkAll: false,
				isIndeterminate: false,
				createParam: {
					pages: [],
					ids: [],
					packageName: '',
					generatePath: '',
				},
				createRules: {
					packageName: [{required: true, message: '请输入包名', trigger: 'blur'}],
					generatePath: [{required: true, message: '请输入代码生成路径', trigger: 'blur'}]
				}
			};
		},
		/**
		 * 初始化函数
		 */
		created() {
			//获取路由参数
			let params = this.$route.query;
			//动态获取路由参数的key值
			let keys = Object.values(params).join("");
			this.value = keys;
			this.handleDicts();
		},
		/**
		 * 挂载函数
		 */
		mounted() {
			//调用表格数据方法
			this.getList();
		},
		/**
		 * 方法
		 */
		methods: {
			/** 打开导入表弹窗 */
			openImportTable() {
				this.$refs.import.show();
			},
			/**
			 * 切换modal显示状态
			 * @param {String} type 'modify' || 'increase'
			 * @param {Boolean} isShow
			 * @param {Object} value
			 */
			ChangetoggleModal(type, isShow, value) {
				this.$refs[`${type}Modal`].updateModal(isShow, value);
			},
			//表单设计
			handleSjForm(row) {
				let href = `${process.env.VUE_APP_Form_URL}?formId=${row.id}`;
				window.open(href, "_blank");
			},
			/*
			 * 表格多选框选中数据，按钮状态改变
			 */
			handleSelectionChange(selection) {
				this.ids = selection.map(item => item.id);
				this.multiple = !selection.length;
			},
			/**
			 * 获取分页参数
			 */
			pagination({
				page,
				limit
			}) {
				this.queryParams.pageNum = page;
				this.queryParams.pageSize = limit;
				this.getList();
			},
			/**
			 * 重置表单
			 */
			resetQuery() {
				this.$refs.queryForm.resetFields();
				this.getList();
			},
			/**
			 * 查询方法
			 */
			handleQuery() {
				//设置默认进入第一页
				this.queryParams.pageNum = 1;
				//获取列表数据
				this.getList();
			},
			/**
			 * 获取表格列表
			 */
			async getList() {
				//设置Loding状态
				this.loading = true;
				//调用列表查询接口
				api.sysFormTable.list(this.queryParams).then(res => {
					//判断返回状态
					if (res.code) {
						//设置列表数据
						this.tableList = res.rows;
						//设置总条目数
						this.total = res.total;
					} else {
						this.$message.error(res.msg);
					}
					//loading结束
					this.loading = false;
				}).catch(err => {
					this.$message.error(err.msg)
				});
			},
			/**
			 * 删除数据
			 * @param {Object} node
			 */
			handleDelete(node) {
				ElMessageBox.confirm("此操作将永久删除该文件, 是否继续?", "提示", {
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning"
					})
					.then(() => {
						//调用删除接口
						api.sysFormTable
							.del(node.id)
							.then(res => {
								//重新获取列表
								this.getList();
								//弹出提示
								ElMessage({
									type: "success",
									message: "删除成功!"
								});
							})
							.catch(err => {
								ElMessage({
									type: "error",
									message: "删除失败!"
								});
							});
					})
					.catch(err => {
						ElMessage({
							type: "error",
							message: "已取消!"
						});
					});
			},
			/** 导出按钮操作 */
			handleExport() {
				api.sysFormTable
					.ExportData()
					.then(res => {
						const link = document.createElement("a");
						let blob = new Blob([res], {
							type: res.type
						});
						link.style.display = "none";
						link.href = URL.createObjectURL(blob);
						link.setAttribute("download", "表单管理表统计数据");
						document.body.appendChild(link);
						link.click();
						document.body.removeChild(link);
					})
					.catch(err => {
						this.$message.error("导出失败");
					});
			},
			/**
			 * 添加
			 */
			handleAdd() {
				this.$router.push("/sysFormTableFormModal");
			},
			/**
			 * 编辑
			 */
			handleUpdate(row) {
				this.isType = "edit"; //根据状态判断是否请求详情接口
				this.$router.push({
					path: "/sysFormTableFormModal",
					query: {
						id: row.id,
						isType: this.isType
					}
				});
			},
			/**
			 * 详情字段
			 */
			handledetails(row, type) {
				//点击按钮显示组件
				this.FlagShow = true
				this.formList = row;
				// this.$refs.FormField.DialogShow = true;

				// this.$router.push({
				//   path: "/sysFormField",
				//   query: { tableId: row.id }
				// });
			},
			/**
			 * 生成代码
			 */
			handleCheckAllChange(val) {
				this.createParam.pages = val ? this.optionsArr : []
				this.isIndeterminate = false
			},
			handleCheckedCitiesChange(value) {
				const checkedCount = value.length
				  this.checkAll = checkedCount === this.optionsArr.length
				  this.isIndeterminate = checkedCount > 0 && checkedCount < this.optionsArr.length
			},
			generateCode(row) {
				this.dialogVisible = true;
				this.createParam.ids[0] = row.id;
			},
			submitCreate(ids) {
				this.$refs.createForm.validate(valid => {
					if(valid) {
						if(this.createParam.pages.length == 0) return this.$message.error('请选择要生成的模块！');
						//调用删除接口
						api.sysFormTable
							.generateCode(this.createParam)
							.then(res => {
								if(res.code == 200) {
									ElMessage({
										type: "success",
										message: '代码生成成功'
									});
									this.dialogVisible = false;
								}else {
									ElMessage({
										type: "error",
										message: res.msg
									});
								}
							})
							.catch(err => {
								ElMessage({
									type: "error",
									message: err.msg
								});
							});
					}
				})
				
				
			},
			cancleCreate() {
				this.dialogVisible = false; 
				this.checkAll = false; 
				this.checkList = []; 
				this.createParam.pages = [];
				this.isIndeterminate = false;
				this.$refs.createForm.resetFields()
			},
			handleDicts(){
			    getDicts('scdmlx').then((res)=>{
			        this.optionsArr = res.data.map((modal)=>{
			            // let label = {
			            //     label:modal.dictLabel,
			            //     value:modal.dictValue
			            // };
			            return modal.dictValue
			        })
			    });
					getConfigKey('packageName').then(res => {
						if(res.code == 200) {
							this.createParam.packageName = res.data;
						}else {
							this.$message.error(res.msg)
						}
					})
					getConfigKey('generatePath').then(res => {
						if(res.code == 200) {
							this.createParam.generatePath = res.data;
						}else {
							this.$message.error(res.msg)
						}
					})
					
			}
		}
	};
</script>

<style lang="less" scoped>
	:deep(.create-pro) {
		position: absolute;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		background: #fff;
		box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.12), 0 0 6px 0 rgba(0, 0, 0, 0.04);
		z-index: 9;
	}
	.createItem {
		display: flex;
		align-items: center;
		span {
			
		}
	}
</style>
